<template>
  <div>
    <div class="comm">
      <div class="comm_1">
        <van-search
          v-model="params.name"
          shape="round"
          background="#f7f8fa"
          placeholder="请输入搜索关键词"
          use-action-slot
          @search="onSearch"
          @cancel="onCancel"
          right-icon="../../images/12.png"
        />
      </div>

      <div @click="toMassage">
        <van-image
          src="../../images/chat.png"
          style="height: 35px; margin-top: 15px"
        />
      </div>
    </div>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <div class="image_box">
        <van-image src="../../images/1.jpg" class="image" />
      </div>

      <div class="image_2">
        <div class="totil">直播免费鉴宝</div>
        <div class="totil_2">累计鉴定超过100000</div>

        <div
          ref="draggableBox"
          class="list"
          @mousedown.prevent="startDrag"
          @mousemove="onDrag"
          @mouseup="stopDrag"
          @mouseleave="stopDrag"
          @touchstart.prevent="startDragTouch"
          @touchmove="onDragTouch"
          @touchend="stopDrag"
          @touchcancel="stopDrag"
          :style="{ transform: `translateX(${position.x}px)` }"
        >
          <div class="image_3">
            <van-image round width="60" height="60" src="../../images/5.jpg" />
            <p>欧阳心怡</p>
          </div>
          <div class="image_3">
            <van-image round width="60" height="60" src="../../images/6.jpg" />
            <p>王小五</p>
          </div>
          <div class="image_3">
            <van-image round width="60" height="60" src="../../images/7.jpg" />
            <p>刘晨曦</p>
          </div>
          <div class="image_3">
            <van-image round width="60" height="60" src="../../images/10.jpg" />
            <p>孙宛如</p>
          </div>
          <div class="image_3">
            <van-image
              style="width: 100%; height: 100%"
              round
              src="../../images/11.jpg"
            />
            <p>周小艺</p>
          </div>
          <div class="image_3">
            <van-image round width="60" height="60" src="../../images/5.jpg" />
            <p>欧阳心怡</p>
          </div>
          <div class="image_3">
            <van-image round width="60" height="60" src="../../images/5.jpg" />
            <p>欧阳心怡</p>
          </div>
          <div class="image_3">
            <van-image round width="60" height="60" src="../../images/5.jpg" />
            <p>欧阳心怡</p>
          </div>
          <div class="image_3">
            <van-image round width="60" height="60" src="../../images/5.jpg" />
            <p>欧阳心怡</p>
          </div>
          <div class="image_3">
            <van-image round width="60" height="60" src="../../images/5.jpg" />
            <p>欧阳心怡</p>
          </div>
        </div>
      </div>
      <div>
        <div class="tity">
          <van-tabs  v-model:active="activeTab" :swipeable="true">
            <div>
              <van-tab title="推荐" name="a">
                <template #title>
                  <span :class="['tab-text', activeTab === 'a' ? 'active-tab' : '']">推荐</span>
                </template>
              </van-tab>
            </div>
            <div>
              <van-tab title="玉翠珠宝" name="b">
                <template #title>
                  <span :class="['tab-text', activeTab === 'b' ? 'active-tab' : '']">玉翠珠宝</span>
                </template>
              </van-tab>
            </div>
            <div>
              <van-tab title="工艺作品" name="c">
                <template #title>
                  <span :class="['tab-text', activeTab === 'c' ? 'active-tab' : '']">工艺作品</span>
                </template>
              </van-tab>
            </div>
            <div>
              <van-tab title="文玩杂项" name="d">
                <template #title>
                  <span :class="['tab-text', activeTab === 'd' ? 'active-tab' : '']">文玩杂项</span>
                </template>
              </van-tab>
            </div>
            <div>
              <van-tab title="钱币邮票" name="e">
                <template #title>
                  <span :class="['tab-text', activeTab === 'e' ? 'active-tab' : '']">钱币邮票</span>
                </template>
              </van-tab>
            </div>
          </van-tabs>
          <div><van-icon name="apps-o" @click="router.push('/classify')" />分类</div>
        </div>
      </div>

      <div class="get">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <van-row gutter="20">
            <van-col
              span="12"
              v-for="(item, index) in items"
              :key="index"
              class="pro_box"
            >
              <div class="item-info" @click="a(item.id)">
                <van-image :src="item.picture" />
                <p>{{ item.name }}</p>
                <p style="color: red">￥{{ item.price }}</p>
              </div>
            </van-col>
          </van-row>
        </van-list>
      </div>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { getProList } from "@/api/product/product.js";
import { useRouter } from "vue-router";

// 加载状态
const loading = ref(false);
// 是否已经加载完毕
const finished = ref(false);
const refreshing = ref(false);
const items = ref([]);
const params = ref({ name: "", page: 0, pageSize: 6 });
const total = ref(0);
const router = useRouter();

const draggableBox = ref(null);
const isDragging = ref(false);
const position = ref({ x: 0 });
let startX = 0;
let startScrollX = 0;

const startDrag = (event) => {
  isDragging.value = true;
  startX = event.clientX;
  startScrollX = position.value.x;
  document.addEventListener("mousemove", onDrag);
  document.addEventListener("mouseup", stopDrag);
};

const onDrag = (event) => {
  if (!isDragging.value) return;
  const dx = event.clientX - startX;
  position.value.x = Math.max(
    -window.innerWidth,
    Math.min(startScrollX + dx, 0)
  );
};

const stopDrag = () => {
  isDragging.value = false;
  document.removeEventListener("mousemove", onDrag);
  document.removeEventListener("mouseup", stopDrag);
};

const startDragTouch = (event) => {
  if (event.touches.length !== 1) return;
  isDragging.value = true;
  startX = event.touches[0].clientX;
  startScrollX = position.value.x;
  document.addEventListener("touchmove", onDragTouch);
  document.addEventListener("touchend", stopDrag);
  document.addEventListener("touchcancel", stopDrag);
};

const onDragTouch = (event) => {
  if (!isDragging.value || event.touches.length !== 1) return;
  const dx = event.touches[0].clientX - startX;
  position.value.x = Math.max(
    -window.innerWidth,
    Math.min(startScrollX + dx, 0)
  );
};

function a(i) {
  console.log(i);
  router.push({
    name: "Detailpage",
    query: { id: i },
  });
}

function toMassage() {
  router.push({ name: "discover" });
}



// 添加一个超时控制的 Promise
const timeoutPromise = (timeout) => {
  return new Promise((_, reject) => {
    setTimeout(() => reject(new Error('请求超时')), timeout)
  })
}

// 添加一个延时函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))

async function onLoad() {
  try {
    // 设置加载状态
    loading.value = true
    
    // 如果是刷新或重试，重置页码
    if (params.value.page === 0) {
      items.value = []
      finished.value = false
    }
    
    params.value.page = params.value.page + 1

    // 添加超时控制，设置 5 秒超时
    const result = await Promise.race([
      getProList(params.value),
      timeoutPromise(5000)
    ])

    if (result.code === 200) {
      // 更新数据
      total.value = result.data.total
      items.value.push(...result.data.list)

      // 判断是否加载完毕
      if (items.value.length >= total.value || result.data.list.length === 0) {
        finished.value = true
      }
    } else {
      throw new Error('请求失败')
    }

  } catch (error) {
    console.error('加载数据失败:', error)
    
    // 重置页码到第一页
    params.value.page = 0
    
    // 如果不是第一页的数据，自动重试
    if (items.value.length > 0) {
      await delay(1000) // 等待1秒后重试
      onLoad() // 重试加载
    }
  } finally {
    // 无论成功失败，延迟1秒后再关闭加载状态
    await delay(1000)
    loading.value = false
  }
}

// 刷新函数也需要相应修改
async function onRefresh() {
  try {
    refreshing.value = true
    params.value.page = 0
    finished.value = false
    await onLoad()
  } finally {
    await delay(1000)
    refreshing.value = false
  }
}

function onSearch() {
  params.value.page = 0;
  items.value = [];
  onLoad();
}
function onCancel() {}

const activeTab = ref('a');
</script>

<style>
.item-info {
  margin: 10px 0;
  border-radius: 20px;
  overflow: hidden;
  height: 260px;
}

.get {
  width: 95%;
  margin: 0 auto;
}
.van-search {
  padding: 0;
  margin: 10px 10px 0 0;
  border: 1px solid red;
  border-radius: 10px;
}
.comm {
  overflow: hidden;
  display: flex;
  height: 50px;
  width: 95%;
  margin: 10px auto;
  margin-bottom: 5px;
}
.comm_1 {
  width: 95%;
  padding: 0;
}

.image {
  width: 100%;
  height: 200px;
  border-radius: 10px;
  overflow: hidden;
}
.image_box {
  width: 95%;
  margin: 0 auto;
}
.image_2 {
  width: 95%;
  height: 140px;
  background-image: url("../../2.jpg");
  margin: 10px auto;
  border-radius: 10px;
  color: black;
  position: relative;
  overflow: hidden;
}
.totil {
  position: absolute;
  width: 40%;
  left: 15px;
  top: 5px;
  font-size: 20px;
  font-weight: 700;
}
.totil_2 {
  width: 40%;
  right: 20px;
  position: absolute;
  top: 10px;
  color: red;
}
.list {
  margin-top: 40px;
  width: 200vw; /* 设置盒子宽度为页面宽度的200% */
  height: 90px;
  position: relative;
  display: flex;
  overflow: hidden;
  white-space: nowrap; /* 防止内容换行 */
}
.image_3 {
  font-size: 12px;
  text-align: center;
  margin: 0 10px;
  width: 60px;
  height: 60px;
  margin-top: 10px;
}
.tity {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px;
  background: #fff;
  height: 44px;
  border-bottom: 1px solid #f5f5f5;
}

:deep(.van-tabs) {
  flex: 1;
}

:deep(.van-tabs__wrap) {
  height: 40px;
}

:deep(.van-tabs__nav) {
  background: transparent;
  padding: 0 8px;
}

:deep(.van-tab) {
  padding: 0 16px;
  min-width: auto;
  flex: none !important;
}

.tab-text {
  font-size: 15px;
  color: #666;
  white-space: nowrap;
  display: inline-block;
  line-height: 40px;
  padding: 0 2px;
}

.active-tab {
  color: #ee0a24 !important;
  font-weight: 500;
}

:deep(.van-tabs__line) {
  background-color: #ee0a24 !important;
  height: 2px;
  width: 20px !important;
  bottom: 4px;
  border-radius: 1px;
}

:deep(.van-tab--active) {
  color: #ee0a24 !important;
}

.tity > div:last-child {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 0 0 0 16px;
  font-size: 14px;
  color: #666;
  border-left: 1px solid #eee;
  height: 100%;
}

.tity .van-icon {
  font-size: 16px;
}

:deep(.van-tabs__content) {
  display: none;
}

:deep(.van-tabs__nav--line) {
  padding-bottom: 0;
}

:deep(.van-tabs__nav) {
  background: transparent !important;
  &::after {
    display: none;
  }
}

:deep(.van-hairline--top-bottom::after),
:deep(.van-hairline-unset--top-bottom::after) {
  display: none;
}

:deep(.van-tab--active) {
  color: #ee0a24 !important;
}

.active-tab {
  color: #ee0a24 !important;
  font-weight: 500;
}

/* 移除所有默认的边框和线条 */
:deep(.van-tabs__nav) {
  border: none !important;
  &::after {
    display: none !important;
  }
}

:deep(.van-tabs__wrap) {
  &::after {
    display: none !important;
  }
}

/* 自定义下划线样式 */
:deep(.van-tabs__line) {
  background-color: #ee0a24 !important;
  height: 2px !important;
  width: 20px !important;
  bottom: 4px !important;
  border-radius: 1px !important;
  z-index: 1 !important;
}

/* 移除所有可能的边框线 */
:deep(.van-hairline--top-bottom::after),
:deep(.van-hairline-unset--top-bottom::after),
:deep(.van-hairline--bottom::after) {
  display: none !important;
}

/* 确保激活状态的样式 */
:deep(.van-tab--active) {
  color: #ee0a24 !important;
  font-weight: normal !important;
}

/* 移除tabs内容区域的边框 */
:deep(.van-tabs__content) {
  border: none !important;
}

/* 移除所有可能的背景色 */
:deep(.van-tabs),
:deep(.van-tabs__wrap),
:deep(.van-tabs__nav) {
  background: transparent !important;
}
</style>
